import React, { useState, useEffect } from 'react';
import { Select, Button, Space, Table, Switch } from 'antd';
import { PlusOutlined, OrderedListOutlined } from '@ant-design/icons';
import * as service from '../../../../../api/salary.js'
import type { ColumnsType } from 'antd/es/table';
import '../Field/Field.scss'
import { DndContext } from '@dnd-kit/core';
import { arrayMove, SortableContext, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import type { DragEndEvent } from '@dnd-kit/core';

function Field(props: any) {
  const [dataSource, setDataSource] = useState([]);
  useEffect(() => {
    service.File_Settings({}).then((res: any) => { //请求薪资档案字段设置列表
      // console.log(res);
      setDataSource(res.data)
    })
  }, [])
  interface DataType {
    key?: string;
    name: string;
    age: number;
    address: string;
    id: string;
  }
  interface RowProps extends React.HTMLAttributes<HTMLTableRowElement> {
    'data-row-key': string;
  }
  const columns: ColumnsType<DataType> = [
    {
      key: 'sort',
    },
    {
      title: '字段名称',
      dataIndex: 'file_name',
    },
    {
      title: '字段类型',
      dataIndex: 'file_type',
    },
    {
      title: '字段提示',
      render: (text) => <a>——</a>
    },
    {
      title: '是否启用',
      render: (_: any, record: any) => <Switch checked={record.isTrue} />
    },
    {
      title: '来源',
      dataIndex: 'come',
    },
    {
      title: '操作',
      render: (_, record) => <a onClick={()=>{handleClick(record.id)}}>删除</a>
    },
  ];
  const Row = ({ children, ...props }: RowProps) => {
    const {
      attributes,
      listeners,
      setNodeRef,
      setActivatorNodeRef,
      transform,
      transition,
      isDragging,
    } = useSortable({
      id: props['data-row-key'],
    });
    const style: React.CSSProperties = {
      ...props.style,
      transform: CSS.Transform.toString(transform && { ...transform, scaleY: 1 }),
      transition,
      ...(isDragging ? { position: 'relative', zIndex: 9999 } : {}),
    };
    return (
      <tr {...props} ref={setNodeRef} style={style} {...attributes}>
        {React.Children.map(children, (child) => {
          if ((child as React.ReactElement).key === 'sort') {
            return React.cloneElement(child as React.ReactElement, {
              children: (
                <OrderedListOutlined
                  ref={setActivatorNodeRef}
                  style={{ touchAction: 'none', cursor: 'move' }}
                  {...listeners}
                />
              ),
            });
          }
          return child;
        })}
      </tr>
    )
  }
  const onDragEnd = ({ active, over }: DragEndEvent) => {
    if (active.id !== over?.id) {
      setDataSource((previous) => {
        const activeIndex = previous.findIndex((i: any) => i.key === active.id);
        const overIndex = previous.findIndex((i: any) => i.key === over?.id);
        return arrayMove(previous, activeIndex, overIndex);
      });
    }
  };
  var handleClick = async (id: any) => { //删除单条
    var res = await service.delete_Settings({ id })
    // console.log(res);
    service.File_Settings({}).then((res: any) => { //请求薪资档案字段设置列表
      // console.log(res);
      setDataSource(res.data)
    })
}
  return (
    <div className='field'>
      <div className='field-one'>
        <div className='field-title-left'></div>
        <h4 className='field-title'>薪资档案字段设置</h4>
      </div>
      <div className='field-two'>
        <b>拖拽可进行字段排序</b>
      </div>
      <div className='field-three'>
        <DndContext onDragEnd={onDragEnd}>
          <SortableContext
            items={dataSource.map((i: any) => i.key)}
            strategy={verticalListSortingStrategy}
          >
            <Table
              components={{
                body: {
                  row: Row,
                },
              }}
              rowKey="key"
              columns={columns}
              dataSource={dataSource}
            />
          </SortableContext>
        </DndContext>
      </div>
    </div>
  );
}

export default Field;